package logic

import (
	"fmt"
	"math"
	"net/http"
	"strconv"
	"strings"
	"tiktok/dao"
	"tiktok/models"
	"time"

	"github.com/gin-gonic/gin"
)

type feedmsg struct {
	models.Status
	Video_list []videos `json:"video_list"`
	Next_time  int64    `json:"next_time"`
}

type dbvideo struct {
	models.Video
	SubTime int64 `gorm:"sub_time"`
}

func Feed(ctx *gin.Context) {
	var last_time int64
	temp := ctx.Query("last_time")
	if temp == "" || temp == "0" { //获取last_time
		last_time = time.Now().Unix()
	} else {
		temp, err := strconv.Atoi(temp)
		judgeErr(err, ctx, "strconv.Atoi:转换失败...")
		last_time = int64(temp)
	}
	//token := ctx.Query("token")
	db := dao.GetDB(ctx)

	video := make([]dbvideo, 0, 40)
	videores := make([]videos, 0, 40)                                                                                    //list_video中
	err := db.Table("tiktok_video").Where("sub_time < ?", last_time).Order("sub_time desc").Limit(30).Find(&video).Error //视频列表
	judgeErr(err, ctx, "feed:db.select:视频列表查询失败...")

	type uuid struct {
		Uid int64 `gorm:"author_id"`
	}

	var next_time int64 = 0x3f3f3f3f3f3f3f3f
	for i := 0; i < len(video); i++ {
		var authorid uuid
		err := db.Table("tiktok_video").Select("author_id").Where("vid = ?", video[i].Vid).Find(&authorid.Uid).Error //视频作者的uid
		judgeErr(err, ctx, "feed:db.select:视频作者uid查询失败...")                                                          //select查询一个参数时？？？

		var author models.User
		err = db.Table("tiktok_user").Where("uid = ?", authorid.Uid).Find(&author).Error //视频作者的信息
		judgeErr(err, ctx, "feed:db.select:视频作者信息查询失败...")
		video[i].Author = author

		next_time = int64(math.Min(float64(next_time), float64(video[i].SubTime))) //next_time

		type love_videos struct {
			lvideo string `gorm:"love_video"` //喜欢列表对应的字符串
		}
		var love_video love_videos
		err = db.Table("tiktok_user").Select("love_video").Where("uid = ?", video[i].Author.Uid).Find(&love_video.lvideo).Error //喜欢列表
		judgeErr(err, ctx, "feed:db.select:喜欢列表查询失败...")

		str := "/" + strconv.FormatInt(video[i].Vid, 10) + "/" //判断是否喜欢
		if ok := strings.Contains(love_video.lvideo, str); ok {
			video[i].IsFavorite = true
		} else {
			video[i].IsFavorite = false
		}

		videores = append(videores, videos{video[i].Video})
	}

	fmt.Println(videores, next_time)
	ctx.JSON(http.StatusOK, feedmsg{
		Status: models.Status{
			StatusCode: 0,
			StatusMsg:  "查询成功!",
		},
		Video_list: videores,
		Next_time:  time.Now().Unix(), //next_time,
	})
}
